﻿using System;
using System.Text;

namespace Douya.Json
{
    public class JsonWriter
    {
        int indent = 2;

        public string Write(JsonObject JsonObj)
        {
            StringBuilder builder = new StringBuilder();
            WriteObject(builder, 0, JsonObj);
            return builder.ToString();
        }

        void WriteObject(StringBuilder builder, int level, JsonObject JsonObj)
        {
            builder.Append("{");
            builder.Append("\n");

            foreach (String name in JsonObj.Keys)
            {
                builder.Append(' ', (level + 1) * indent);
                IJsonValue value = JsonObj.GetValue(name);
                if (value.Type == ValueType.TypeObject)
                {
                    builder.AppendFormat("\"{0}\": ", name);
                    WriteObject(builder, level + 1, (JsonObject)value);
                }
                else if (value.Type == ValueType.TypeArray)
                {
                    builder.AppendFormat("\"{0}\": ", name);
                    WriteArray(builder, level + 1, (JsonArray)value);
                }
                else
                {
                    builder.AppendFormat("\"{0}\": {1}", name, value.ToString());
                }
                builder.Append(",\n");
            }
            if (JsonObj.Count > 0)
            {
                builder.Length -= 2;
            }
            builder.Append("\n");

            builder.Append(' ', level * indent);
            builder.Append("}");
        }

        void WriteArray(StringBuilder builder, int level, JsonArray JsonAry)
        {
            builder.Append("[");
            builder.Append("\n");

            for (int i = 0; i < JsonAry.Count; ++i)
            {
                builder.Append(' ', (level + 1) * indent);
                IJsonValue value = JsonAry.GetValue(i);
                if (value.Type == ValueType.TypeObject)
                {
                    WriteObject(builder, level + 1, (JsonObject)value);
                }
                else if (value.Type == ValueType.TypeArray)
                {
                    WriteArray(builder, level + 1, (JsonArray)value);
                }
                else
                {
                    builder.Append(value.ToString());
                }
                builder.Append(",\n");
            }
            if (JsonAry.Count > 0)
            {
                builder.Length -= 2;
            }
            builder.Append("\n");

            builder.Append(' ', level * indent);
            builder.Append("]");
        }
    }
}
